<?php
namespace App\Api\Controllers;
use Common\ApiController;
use Common\Common;
use Common\Models\OrderCommissions;
use Common\Models\Orders;
use Common\Models\User;

class FansController extends ApiController
{
	public function initialize()
	{
		parent::initialize();
	}

    /**
     * @func 粉丝列表
     * @param type 1 潜在粉丝 2 直推粉丝 3 推荐粉丝
     */
    public function fans_listAction()
    {
        $data = [];
        //关键词查找
        if (!isset($this->params['keyword']) || empty($this->params['keyword'])) {
            $data['keyword'] = '';
        } else {
            $data['keyword'] = $this->params['keyword'];
        }

        if (!isset($this->params['type']) || empty($this->params['type'])) {      //类型 1潜在 2直推 3间接
            $data['type'] = 2;
        } else {
            if ($this->params['type'] != 1 || $this->params['type'] != 2 || $this->params['type'] != 3) {
                $data['type'] = $this->params['type'];
            } else {
                $this->fail(-1, '类型参数错误');
            }
        }

        if (isset($this->params['created_at']) && !empty($this->params['created_at'])) {
            switch ($this->params['created_at']) {
                case 1:
                    $data['created_at'] = Common::timeChange(1);
                    break;
                case 8:
                    $data['created_at'] = Common::timeChange(8);
                    break;
                default:
                    $this->fail(-1, '时间格式错误');
                    break;
            }
        }


        //创建时间 排序
        if (isset($this->params['jointime']) && !empty($this->params['jointime'])) {
            $jointime = strtoupper($this->params['jointime']);
            if ($jointime == 'DESC' || $jointime == 'ASC') {
                $data['jointime'] = $jointime;
            } else {
                $this->fail(-1, '时间排序参数错误');
            }
        } else {
            $data['jointime'] = '';
        }

        //团队规模 排序
        if (isset($this->params['team_scale']) && !empty($this->params['team_scale'])) {
            $team_scale = strtoupper($this->params['team_scale']);
            if ($team_scale == 'DESC' || $team_scale == 'ASC') {
                $data['team_scale'] = $team_scale;
            } else {
                $this->fail(-1, '团队规模排序参数错误');
            }
        } else {
            $data['team_scale'] = '';
        }


        //等级查找
        if (isset($this->params['level_id']) && !empty($this->params['level_id'])) {
            $data['level_id'] = $this->params['level_id'];
        } else {
            $data['level_id'] = '';
        }


        //当前页数
        if (!isset($this->params['page']) || empty($this->params['page'])) {
            $page = Common::PAGE;
        } else {
            $page = (int)$this->params['page'];
        }

        //当前条数
        if (!isset($this->params['page_size']) || empty($this->params['page_size'])) {
            $pageSize = Common::PAGESIZE;
        } else {
            $pageSize = (int)$this->params['page_size'];
        }

        $user = new User();
        $orderCommonssion = new OrderCommissions();
        $flag = "count";
        switch ($data['type']) {
            case 1://潜在
                $user_list = $user->listByWhere_self($this->user_info['id'], $data, $pageSize, $page);
                $user_list_count = $user->listByWhere_self($this->user_info['id'], $data, $pageSize, $page, $flag);
                break;
            case 2://直推
                $user_list = $user->listByWhere_self($this->user_info['id'], $data, $pageSize, $page);
                $user_list_count = $user->listByWhere_self($this->user_info['id'], $data, $pageSize, $page, $flag);
                break;
            case 3://间接
                if ($this->user_info['path'] == 0 && $this->user_info['path'] == '') {
                    if ($this->user_info['referer_id'] != 0) {
                        $path = '0,' . $this->user_info['referer_id'];
                    } else {
                        $path = $this->user_info['referer_id'];
                    }
                    $pathArr = explode(',', $path);
                } else {
                    $path = $this->user_info['path'] . ',' . $this->user_info['referer_id'];
                    $pathArr[0] = $path;
                }
                $path = implode(',', $pathArr);
                $data['path'] = $path . ',' . $this->user_info['id'];
                $user_list = $user->listByWhere_self($this->user_info['id'], $data, $pageSize, $page);
                $redis_key = 'fans_' . $this->user_info['id'];
                $user_list_count = $this->cache->get_cache($redis_key);
                if (!$user_list_count) {
                    $user_list_count = $user->listByWhere_self($this->user_info['id'], $data, $pageSize, $page, $flag);
                    $this->cache->set_cache($redis_key, $user_list_count, 60);
                }
                break;
            default:
                $pathArr = [];
                if (!empty($this->user_info['path'] != '')) {
                    $pathArr = explode(',', $this->user_info['path']);
                } else {
                    $user_id = '0,' . $this->user_info['id'];
                    $pathArr = explode(',', $user_id);
                }
                $data['path'] = implode(',', $pathArr);
                $user_list = $user->listByWhere_self($this->user_info['id'], $data, $pageSize, $page);
                $user_list_count = $user->listByWhere_self($this->user_info['id'], $data, $pageSize, $page, $flag);
        }
        $user_list = Common::transition_array($user_list);
        $list = Common::paging($user_list,$user_list_count,$pageSize,$page);
        foreach ($list['items'] as $key => $value) {
            if ($value['nickname'] || $value['wx_nickname'] || $value['phone']) {             //获取当前我的昵称 判断 以前的nickname 后面添加了一个wx_nickname 如果没有的话就取电话号码
                $username = $value['nickname'] ? $value['nickname'] : $value['wx_nickname'];
                if (empty($username)) {
                    $phone = substr_replace($value['phone'], '****', 3, 4);
                    $username = $phone;
                }
            } else {
                $username = '没有填写';
            }
            unset($list['items'][$key]['wx_nickname']);
            $list['items'][$key]['nickname'] = $username;
            $list['items'][$key]['phone'] = substr_replace($value['phone'], '****', 3, 4);

            $today_start_end_time=Common::timeChange(1); //今日
            $time_data['start_end_time']=$today_start_end_time;
            $list['items'][$key]['today_user_estimate'] = $user->getDirectFansCount($value['id'],$time_data);//查询直接邀请粉丝数量（直邀）
            $list['items'][$key]['money_today_estimate'] = sprintf("%.2f",array_sum($orderCommonssion->getOrderChannelEstimateCommission($value['id'],$today_start_end_time)));

            $month_start_end_time=Common::timeChange(8);//本月
            $time_data['start_end_time']=$month_start_end_time;
            $list['items'][$key]['month_user_estimate'] = $user->getDirectFansCount($value['id'],$time_data);//查询直接邀请粉丝数量（直邀）
            $list['items'][$key]['money_month_estimate'] = sprintf("%.2f",array_sum($orderCommonssion->getOrderChannelEstimateCommission($value['id'],$month_start_end_time)));
        }
        $this->ok($list['items']);
    }





    /**
     * @func 粉丝数量
     */
    public function fans_numberAction(){
        if($this->user_info['path'] == 0 && $this->user_info['path']== '') {
            if($this->user_info['referer_id'] != 0 ) {
                $path = '0,' . $this->user_info['referer_id'];
            }else{
                $path = $this->user_info['referer_id'];
            }
            $pathArr = explode(',', $path);
            //array_push($pathArr, $this->user_info['referer_id']);
        }else{
            $path = $this->user_info['path'].','.$this->user_info['referer_id'];
            $pathArr[0] = $path;
        }
        $path = implode(',', $pathArr);
        $user = new User();

        //总粉丝数
        $data['start_end_time'] = 0;
        $result['totalCount']=$user->getInviteFansCount($this->user_info['id'],$path,$data);
        //今日新增粉丝数
        $data['start_end_time'] = Common::timeChange(1);
        $result['todayCount']=$user->getInviteFansCount($this->user_info['id'],$path,$data);
        //昨日新增粉丝数
        $data['start_end_time'] = Common::timeChange(2);
        $result['yesterdayCount']=$user->getInviteFansCount($this->user_info['id'],$path,$data);
        //本周新增粉丝
        $data['start_end_time'] = Common::timeChange(14);
        $result['weekCount']=$user->getInviteFansCount($this->user_info['id'],$path,$data);
        //直属粉丝数
        $data['start_end_time'] = 0;
        $result['directCount']=$user->getDirectFansCount($this->user_info['id'],$data);
        //团队粉丝数
        $result['indirectCount']=$user->getIndirectFansCount($this->user_info['id'],$path);

        //直属潜在粉丝
        $data['is_appuser'] = 0;
        $result['unloginCount'] = $user->getDirectFansCount($this->user_info['id'],$data);

        //有效粉丝
        $data['is_buyed']=1;
        $data['start_end_time'] = 0;
        $result['buygoodsCount'] = $user->getInviteFansCount($this->user_info['id'],$path,$data);

        //联盟推荐未登录
        $data['is_appuser']=0;
        unset($data['is_buyed']);
        $result['unloginIndirectCount']=$user->getIndirectFansCount($this->user_info['id'],$path,$data);
        //联盟推荐已登录
        $data['is_appuser']=1;
        $result['loginIndirectCount']=$user->getIndirectFansCount($this->user_info['id'],$path,$data);
        //直属未登录
        $data['is_appuser']=0;
        $result['unlogindirectCount']=$user->getDirectFansCount($this->user_info['id'],$data);
        //直属已登录
        $data['is_appuser']=1;
        $result['logindirectCount']=$user->getDirectFansCount($this->user_info['id'],$data);
        $this->ok($result);
    }



    //------------------------------------------------------------------------------------------------------------------新添加的接口--------------------------------------------------------------

    /**
     * 粉丝首页数据
     */
    public function fans_numAction()
    {
        $userDb             = new User();
        $OrderDb            = new Orders();


        //直邀粉丝
        $referer['referer_id']         = $this->user_info['id'];
        $result['referer_count']       = $userDb->fans_count($referer);
        $referer['is_buyed']           = 1;
        $result['referer_valid_count'] = $userDb->fans_count($referer);

        $data['path']       = $this->user_info['path'];       //总人数
        $all_fans           = $userDb->fans_count_num($this->user_info['id']);
        $result['all_fans'] = $all_fans+$result['referer_count'];

        //间邀粉丝
        $indirect['indirect_id']        = $this->user_info['id'];
        $result['indirect_count']       = $userDb->fans_count($indirect);
        $indirect['is_buyed']           = 1;
        $result['indirect_valid_count'] = $userDb->fans_count($indirect);


        //潜在粉丝
        $latent['referer_id']         = $this->user_info['id'];
        $latent['is_appuser']         = 0;
        $result['latent_count']       = $userDb->fans_count($latent);
        $latent['is_buyed']           = 1;
        $result['latent_valid_count'] = $userDb->fans_count($latent);


        /**
         * 直邀数据
         */
        $referer_arr1['referer_id']          = $this->user_info['id'];        //直邀粉丝
        $referer_arr1['created_at_datetime'] = Common::timeChange(1);
        $result['referer']['today_newuser']  = $userDb->fans_count($referer_arr1);               //今日新增
        unset($referer_arr1['created_at_datetime']);
        $referer_arr1['updated_at_datetime'] = Common::timeChange(1);                //今日活跃

        $result['referer']['active_newuser'] = $userDb->fans_count($referer_arr1);

        $current['day']                         = date("Ymd");//今日首单

        $result['referer']['first_today_order'] = 0;

        $today['order_create_time'] = Common::timeChange(1);                        //今日下单人数
        $referer_ids                = $userDb->referer_ids($this->user_info['id']);
        if ($referer_ids) {
            $today['referer_ids']               = $referer_ids;
            $history['referer_ids']             = $referer_ids;
            $result['referer']['today_order']   = $OrderDb->referer_today_order($today, 'user_id');
            $result['referer']['history_order'] = $OrderDb->referer_today_order($history, 'user_id');
        } else {
            $result['referer']['today_order']   = 0;
            $result['referer']['history_order'] = 0;
        }


        $loster_user['referer_id']          = $this->user_info['id'];
        $loster_user['updated_at_datetime'] = Common::timeChange(15);                            //流失用户
        $result['referer']['loster_user']   = $userDb->fans_count_nologin($loster_user);


        /**
         * 间邀数据
         */
        $indirect_arr1['indirect_id']         = $this->user_info['id'];        //粉丝
        $indirect_arr1['created_at_datetime'] = Common::timeChange(1);
        $result['indirect']['today_newuser']  = $userDb->fans_count($indirect_arr1);               //今日新增

        unset($indirect_arr1['created_at_datetime']);
        $indirect_arr1['updated_at_datetime'] = Common::timeChange(1);                //今日活跃
        $result['indirect']['active_newuser'] = $userDb->fans_count($indirect_arr1);

        //今日首单
        $result['indirect']['first_today_order'] = 0;

        $referer_ids = $userDb->referer_ids($this->user_info['id'], 2);
        if ($referer_ids) {
            $today['referer_ids']                = $referer_ids;
            $history['referer_ids']              = $referer_ids;
            $result['indirect']['today_order']   = $OrderDb->referer_today_order($today, 'user_id');
            $result['indirect']['history_order'] = $OrderDb->referer_today_order($history, 'user_id');
        } else {
            $result['indirect']['today_order']   = 0;
            $result['indirect']['history_order'] = 0;
        }

        $loster_user['indirect_id']         = $this->user_info['id'];
        $loster_user['updated_at_datetime'] = Common::timeChange(15);                            //流失用户
        $result['indirect']['loster_user']  = $userDb->fans_count_nologin($loster_user);


        $result['referer']['today_newuser_msg']     = '111';               //
        $result['referer']['active_newuser_msg']    = '222';               //
        $result['referer']['first_today_order_msg'] = '333';               //
        $result['referer']['today_order_msg']       = '444';               //
        $result['referer']['history_order_msg']     = '555';               //
        $result['referer']['loster_user_msg']       = '666';               //

        $result['indirect']['today_newuser_msg']     = '111';               //
        $result['indirect']['active_newuser_msg']    = '222';               //
        $result['indirect']['first_today_order_msg'] = '333';               //
        $result['indirect']['today_order_msg']       = '444';               //
        $result['indirect']['history_order_msg']     = '555';               //
        $result['indirect']['loster_user_msg']       = '666';               //

        $result['referer__msg'] = 'aaa';
        $result['indirect_msg'] = 'bbb';
        $result['latent_msg']   = 'ccc';
        $this->ok($result);
    }



    /**
     * 粉丝详情
     */
    public function fans_detailsAction()
    {
        if (!isset($this->params['fans_user_id']) || empty($this->params['fans_user_id'])) {
            $this->fail(-1, '缺少fans_user_id');
        }
        $f_users = new User();
        $data    = $f_users->fans_details($this->params['fans_user_id']);
        $this->ok($data);
    }

}
